package code.example.zookeeper.master;

import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * Created by Administrator on 2017/6/16.
 */

public class ZooKeeperMasterSelector {
    static final Logger logger = LoggerFactory.getLogger(ZooKeeperMasterSelector.class.getSimpleName());
    ZookpeerConfig zookpeerConfig;

    public ZookpeerConfig getZookpeerConfig() {
        return zookpeerConfig;
    }

    public void setZookpeerConfig(ZookpeerConfig zookpeerConfig) {
        this.zookpeerConfig = zookpeerConfig;
    }

    String zkPath=null;
    String selectorId ="";
    //选举说明
    String desc = "";
    public String getZkPath() {
        return zkPath;
    }

    public void setZkPath(String zkPath) {
        this.zkPath = zkPath;
    }

    public String getSelectorId() {
        return selectorId;
    }

    public void setSelectorId(String selectorId) {
        this.selectorId = selectorId;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public   String  getServerIp(){
        String SERVER_IP = null;
        try {
            Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                ip = (InetAddress) ni.getInetAddresses().nextElement();
                SERVER_IP = ip.getHostAddress();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress()   && ip.getHostAddress().indexOf(":") == -1) {
                    SERVER_IP = ip.getHostAddress();
                    break;
                } else {
                    ip = null;
                }
            }
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return SERVER_IP;
    }
    public ZooKeeperMasterSelector(){
        try {
            String address = getServerIp();
            if(address != null && address.length()>0){
                selectorId = address;
            }
        }catch (Exception e){}
    }

    public void selectLeader( Runnable runnable){
        if(zkPath == null || zkPath.trim().length()==0){
            throw new RuntimeException("ZooKeeperMasterSelector.zkPath is null");
        }
        if(zookpeerConfig == null){
            throw new RuntimeException("ZooKeeperMasterSelector.zookpeerConfig is null");
        }
        ZookeeperClient client = new ZookeeperClient();
        client.setZookpeerConfig(zookpeerConfig);
        client.leaderLatch(this.zkPath,this.selectorId , new WatchSelect(runnable,this.selectorId,desc));
    }
      class WatchSelect implements LeaderLatchListener {
        Runnable runnable= null;
        String selectorId = null;
        String desc = null;
        public WatchSelect(  Runnable runnable, String selectorId,String desc){
            this.runnable = runnable;
            this.selectorId = selectorId;
            this.desc = desc;
        }


          public void isLeader() {
              logger.info("MasterSelector :" + desc + " ,selectorId:" + selectorId + " is leader");
              try {
                  this.runnable.run();
              }catch (Exception e){
                  logger.info("MasterSelector :" + desc + " ,selectorId:" + selectorId + " is leader,Runnable run error:", e);
              }
          }


          public void notLeader() {

          }
      }
}
